define(["jquery", "easy-admin", "pdfjs"], function ($, ea, pdfjs) {

    var init = {
        table_elem: '#currentTable',
        table_render_id: 'currentTableRenderId',
        index_url: 'insurance.policy/index',
        add_url: 'insurance.policy/add',
        edit_url: 'insurance.policy/edit',
        delete_url: 'insurance.policy/delete',
        export_url: 'insurance.policy/export',
        modify_url: 'insurance.policy/modify',
        stock_url: 'insurance.policy/stock',
        recycle_url: 'insurance.policy/recycle',
        pdf2img_url: 'insurance.policy/pdf2img',
        ocrImg_url: 'insurance.policy/ocrImg',
        billpay_url: 'insurance.policy/billpay',
        setqe_url: 'insurance.policy/setQe',
        renewals_url: 'insurance.policy/renewals',
        set_policy_notice_url: 'insurance.policy/setPolicyNotice',
        import_url: 'insurance.policy/import',
        create_url: 'insurance.policy/create',
        get_history_List_url: 'insurance.policy/gethistoryList',
        supplement_url: 'insurance.policy/supplement',
        batchmodify_url: 'insurance.policy/batchmodify',

    };



    var active = {
        ids: [],
        formdata: [],
        open_index: '',
        methods: {
            analysispdf: function(){
                var analysispdfList = document.querySelectorAll("[data-analysispdf]");
                if (analysispdfList.length > 0) {
                    $.each(analysispdfList, function (i, v) {
                        var uploadName = $(this).attr('data-analysispdf'),
                            elem = "input[name='" + uploadName + "']",
                            uploadElem = this;
                        // 
                        var flag = true;
                        $(this).on('click', function () {
                            if (!flag) {
                                return false;
                            }
                            flag = false;
                            var pdf = $(elem).val();
                            var option = {
                                url: "pdf2ImgOne",
                                data: {pdf: pdf},
                            }
                            var pdf_arr = pdf.split('|');
    
                            var requsetQueue = [];
                            for (var i = 0; i < pdf_arr.length; i++) {
                                requsetQueue.push({url: "pdf2ImgOne", data: {pdf: pdf_arr[i]}});
                            }
                            // 逐个PDF文件转换为图片
                            var lay_index = ea.msg.loading('正在处理中，请稍后...');
                            requsetQueue.reduce((prevPromise, currentReq)=>{
                                return prevPromise.then((prevRes)=>{
                                    return ea.request.fetch(currentReq.url, currentReq.data).then(res => {
                                        prevRes.push({url: "ocrImg", data: res.data});
                                        return prevRes;
                                    })
                                })
                            }, Promise.resolve([]))
                            .then(finalRes => {
                                // 逐个图片识别
                                finalRes.reduce((prevPromise, currentReq)=>{
                                    return prevPromise.then((prevRes)=>{
                                        return ea.request.fetch(currentReq.url, currentReq.data).then(res => {
                                            prevRes.push(res.data);
                                            return prevRes;
                                        })
                                    })
                                }, Promise.resolve([]))
                                .then(finalRes1 => {
                                    console.log("finalRes1", finalRes1);
                                    // mergeData(finalRes1, renderData);
                                    // renderHiddenData(finalRes1);
                                    ea.msg.close(lay_index);
                                    flag = true;
                                })
                                .catch(err => {
                                    ea.msg.error("转换失败,请重试", function(){
                                        ea.msg.close(lay_index);
                                    });
                                    flag = true;
                                })
                            })
                            .catch(err => {
                                ea.msg.error("转换失败,请重试", function(){
                                    ea.msg.close(lay_index);
                                });
                                // console.log(err);
                                flag = true;
                            });
    
                            function mergeData(data, callback){
                                var ocr_res = {};
                                var flag = true;
                                var suffix = {
                                    '1': '_sy',
                                    '2': '_jq',
                                    '3': '_jc'
                                };
                                for (var i = 0; i < data.length; i++) {
                                    for (var key in data[i].mine_data) {
                                        var d = data[i].mine_data;
                                        if (key.indexOf('p_type') > -1) {
                                            ocr_res[key + suffix[d.p_type]] = d[key];
                                            continue;
                                        }
                                        if (key == 'carno' && ocr_res[key] != undefined && ocr_res[key] != d[key]) {
                                            flag = false;
                                            ea.msg.error('车牌号不一致，请检查保单是否同一投被保人');
                                            return;
                                        }
                                        if (key == 'insurer' && ocr_res[key] != undefined && ocr_res[key] != d[key]) {
                                            flag = false;
                                            ea.msg.error('投被保人不一致，请检查保单是否同一投被保人');
                                            return;
                                        }
                                        if (ocr_res[key] == undefined || ocr_res[key] == '') {
                                            ocr_res[key] = d[key];
                                            continue;
                                        }
                                    }
                                }
                                // console.log(ocr_res);
                                flag && callback(ocr_res);
                            }
    
                            function renderData(data){
                                var form = $("#app-form");
                                // var date_key = ['start_at_sy', 'end_at_sy', 'start_at_jq', 'end_at_jq'];
                                var select_key = ['sale_type', 'is_chesun'];
                                for (var key in data) {
                                    // if (date_key.indexOf(key) > -1) {
                                    //     layTimeRender(key, data[key])
                                    // } else 
                                    if (select_key.indexOf(key) > -1) {
                                        // console.log(key, data[key])
                                        form.find('select[name="' + key +'"]').val(data[key])
                                        form.find('select[name="' + key +'"]').trigger('change')
                                        // layui.form.render('select');
                                    } else {
                                        form.find('input[name="' + key +'"]').val(data[key])
                                    }
                                }
                                layui.form.render('select');
                                layui.form.render();
                                $('#cost_sy').trigger('change');
                                $('#cost_jq').trigger('change');
                            }
    
                            function renderHiddenData(data){
                                var keys = [
                                    'file', 'image', 'mine_data', 
                                    'p_type',
                                ];;
                                var suffix = {1: '_sy', 2: '_jq', 3: '_jc'};
                                var form = $("#app-form");
                                for (var i = 0; i < data.length; i++) {
                                    var d = data[i];
                                    // console.log('-------------------------');
                                    // console.log(d)
                                    for (var key of keys) {
                                        // console.log(key, key == 'mine_data')
                                        if (key == 'mine_data') {
                                            d[key] = JSON.stringify(d[key]);
                                        }
                                        form.find('input[name="' + key + suffix[d.p_type] + '"]').val(d[key]);
                                    }
                                }
                            }
    
                        });
                    })
                }
            },
            table_init: function (option){
                option = option || {};
                option.toolbar_custcom = option.toolbar_custcom || [];
                option.where = option.where || {};
                option.searchValue = option.searchValue || {};

                var toolbar_custcom = [
                    {
                        text: '添加',
                        url: init.add_url,
                        method: 'open',
                        auth: 'add',
                        class: 'layui-btn layui-btn-normal layui-btn-sm',
                        icon: 'fa fa-plus ',
                        extend: 'data-width="90%" data-height="95%"',
                    },
                    {
                        text: '结费',
                        url: init.billpay_url,
                        method: 'none',
                        auth: 'billpay',
                        class: 'layui-btn layui-btn-normal layui-btn-sm',
                        icon: '',
                        extend: 'lay-active="billpay" data-url="'+ init.billpay_url +'" data-width="90%" data-height="95%"',
                    },
                    {
                        text: '取消结费',
                        url: init.billpay_url,
                        method: 'none',
                        auth: 'billpay',
                        class: 'layui-btn layui-btn-danger layui-btn-sm',
                        icon: '',
                        extend: 'lay-active="no_billpay" data-url="'+ init.billpay_url +'" data-status="0" data-width="90%" data-height="95%"',
                    },
                    {
                        text: '匹配费用',
                        url: init.setqe_url,
                        method: 'none',
                        auth: 'setqe',
                        class: 'layui-btn layui-btn-normal layui-btn-sm',
                        icon: '',
                        extend: 'lay-active="setqe" data-url="'+ init.setqe_url +'" data-width="90%" data-height="95%"',
                    },
                    {
                        text: '修改',
                        url: init.batchmodify_url,
                        method: 'none',
                        auth: 'setqe',
                        class: 'layui-btn layui-btn-normal layui-btn-sm',
                        icon: '',
                        extend: 'lay-active="batchmodify" data-url="'+ init.batchmodify_url +'" data-width="90%" data-height="95%"',
                    },
                ]
                if (option.toolbar_custcom) {
                    toolbar_custcom = [...toolbar_custcom, ...option.toolbar_custcom];
                }
                var toolbar = [
                    'refresh',
                    toolbar_custcom,
                    'delete', 
                    'export', 
                    // 'recycle'
                ];

                var cols = [[
                    {type: "checkbox"},
                    // {field: 'id', width: 60, title: 'ID', searchOp: '='},
                    {field: 'type', minWidth: 80, title: '保单类型', search: false, templet: function(d) {
                        switch(d.type) {
                            case 1: return '商业';
                            case 2: return '驾乘';
                            case 0: return '交强';
                        }
                    }},
                    {field: 'type', minWidth: 80, title: '维度', search: false, templet: function(d) {
                        var text = '';
                        if (!d.types) return text;
                        for (let item of d.types) {
                            switch(item.type) {
                                case 1: text += '商'; break;
                                case 2: text += '驾'; break;
                                case 0: text += '交'; break;
                            }
                            if (item != d.types[d.types.length - 1]) text += '+';
                        }
                        return text;
                    }},
                    {field: 'agent', width: 80, title: '代理'},
                    {field: 'user.insurer', width: 80, title: '被保险人'},
                    {field: 'user.carno', width: 100, title: '车牌号', searchOp: '=', templet: function(d) {
                        return d.user.carno.slice(0, 2) + '***' + d.user.carno.slice(-2);
                    }},
                    {field: 'section', title: '险种', width: 85, search: false},
                    {field: 'report.amount_me', width: 100, title: 'Me费用', search: false, hide: true},
                    {field: 'report.amount', width: 100, title: '费用', search: false},
                    {field: 'cost', width: 100, title: '保费', search: false},
                    {field: 'vv_tax', width: 100, title: '车船税', search: false, edit: 'text'},
                    {field: 'num', minWidth: 80, title: '保单号', hide: true},
                    {field: 'renewal', width: 100, title: '续保', search: 'select', selectList: {0: '未临期', 1: '30-90天', 2: '30天内', 3: '已过保'}, hide: true},
                    {field: 'is_billpay', title: '费用状态', width: 85, search: 'select', selectList: {0: '未结', 1: '已结'}, templet: function(d) {
                        
                        return d.is_billpay == 1 ? '<span style="color: #f44">已结</span>' : '<span style="color: #ffac44">未结</span>';
                    }},
                    {field: 'create_time', minWidth: 80, title: '创建时间', search: 'range', hide: true},
                    {field: 'agent_factory', minWidth: 80, title: '合作厂', hide: true},
                    {field: 'create_at', minWidth: 80, title: '出单日期', search: 'date'},
                    {
                        width: 250,
                        title: '操作',
                        templet: ea.table.tool,
                        operat: [
                            [
                                {
                                    templet: function (d) {
                                        return `<a class="layui-btn layui-btn-xs" lay-active="downloadFile" data-id="${d.id}" data-file="${d.file}">下载保单 <i class="layui-icon layui-icon-down"></i></a>`
                                    },
                                }, 
                                {
                                    text: '追加保单',
                                    url: init.supplement_url,
                                    method: 'open',
                                    auth: 'supplement',
                                    class: 'layui-btn layui-btn-xs layui-btn-success',
                                    extend: 'data-width="90%" data-height="95%"',
                                },
                                {
                                    text: '编辑',
                                    url: init.edit_url,
                                    method: 'open',
                                    auth: 'edit',
                                    class: 'layui-btn layui-btn-xs layui-btn-success',
                                    extend: 'data-width="90%" data-height="95%"',
                                },
                            ],
                            'delete'
                        ]
                    }
                ]];

                for (var k in cols[0]) {
                    if (cols[0][k].field == undefined) {
                        continue;
                    }
                    for (var i in option.searchValue) {
                        if (cols[0][k].field == i) {
                            cols[0][k].searchValue = option.searchValue[i];
                        }
                    }
                }

                ea.table.render({
                    init: init,
                    toolbar: toolbar,
                    where: option.where,
                    cols: cols,
                    done: function () {
                    }
                });
            },
            table_toolbar_active: function(){
                layui.util.event('lay-active', {
                    no_billpay: function (data) {
                        var that = this;
                        active.event.cc_post(that, '确定要取消结费？', {no: 1});
                    },
                    billpay: function (data) {
                        var that = this;
                        active.event.cc_post(that, '确定要结费？');
                    },
                    setqe: function (data) {
                        var that = this;
                        active.event.cc_post(that, '确定要匹配费用？');
                    },
                    setNotice: function (data) {
                        var that = this;
                        active.event.cc_post(that, '确定要关闭通知？');
                    },
                    downloadFile: function (data) {
                        var that = this;
                        var file = $(that).attr('data-file');
                        var path_root = "http://" + window.location.host + '/';
                        console.log(path_root + file)
                        if (file)
                            window.open(path_root + file)
                    },
                    batchmodify: function (data) {
                        var that = this;
                        var tableId = $(that).attr('data-table');
    
                        tableId = tableId || init.table_render_id;
                        var checkStatus = layui.table.checkStatus(tableId),
                            url = $(that).attr('data-url'),
                            status = $(that).attr('data-status'),
                            data = checkStatus.data;
                        if (data.length <= 0) {
                            ea.msg.error('请勾选需要操作的数据');
                            return false;
                        }
                        active.ids = [];
                        $.each(data, function (i, v) {
                            active.ids.push(v.id);
                        });
                        if (active.ids.length > 0) {
                            active.open_index = layer.open({
                                type: 1, // page 层类型
                                area: ['80%', '80%'],
                                title: '批量修改',
                                shade: 0.6, // 遮罩透明度
                                shadeClose: true, // 点击遮罩区域，关闭弹层
                                maxmin: true, // 允许全屏最小化
                                anim: 0, // 0-6 的动画形式，-1 不开启
                                content: $('#bm-tpl').html(), // 指定内容
                            });
                            layui.form.render();
                        }
                    }, 
                    save: function (data) {
                        var car_type = $('#car_type').val();
                        var agent = $('#agent').val();
                        var is_transfer_owner = $('#is_transfer_owner').val();
                        var is_renewal = $('#is_renewal').val();
                        if (car_type == '' && agent == '' && is_transfer_owner == '' && is_renewal == '') {
                            ea.msg.error('请选择车辆类型或代理人');
                            return false;
                        }
                        var post_data = {ids: active.ids,};
                        if (car_type != '') {
                            post_data.car_type = car_type;
                        }
                        if (agent != '') {
                            post_data.agent = agent;
                        }
                        if (is_transfer_owner != '') {
                            post_data.is_transfer_owner = is_transfer_owner;
                        }
                        if (is_renewal != '') {
                            post_data.is_renewal = is_renewal;
                        }
                        layui.layer.confirm('确定要保存吗？', function(){
                            ea.request.post({
                                url: ea.url(init.batchmodify_url),
                                data: post_data,
                            }, function (res){
                                if (res.code == 1) {
                                    ea.msg.success(res.msg)
                                    layui.layer.close(active.open_index)
                                } else {
                                    ea.msg.error(res.msg)
                                }
                            })
                        })
                    }
                })
            }
        },

        listen: function(){
            active.methods.analysispdf();
        },

        event: {
            cc_post: function(that, msg, extdata) {
                msg = msg || '确定要操作吗？';
                ea.msg.confirm(msg, function(){
                    var tableId = $(that).attr('data-table');
    
                    tableId = tableId || init.table_render_id;
                    var checkStatus = layui.table.checkStatus(tableId),
                        url = $(that).attr('data-url'),
                        status = $(that).attr('data-status'),
                        data = checkStatus.data;
                    if (data.length <= 0) {
                        ea.msg.error('请勾选需要操作的数据');
                        return false;
                    }
                    var ids = [];
                    $.each(data, function (i, v) {
                        ids.push(v.id);
                    });
                    // console.log(url)
                    var post_data = {
                        ids: ids,
                    }
                    if (extdata != undefined && typeof extdata === 'object') {
                        post_data = Object.assign(post_data, extdata);
                    }
                    ea.request.post({
                        url: ea.url(url),
                        data: post_data,
                    }, function (res) {
                        ea.msg.success(res.msg, function () {
                            layui.table.reload(tableId);
                        });
                    });
                })
            }
        },

        render: {
        }
    }

    var pdf = {
        /**
         * 将 PDF 第一页转换为 Base64 图片（PNG 格式）
         * @param {string|ArrayBuffer} pdfSource - PDF 文件 URL 或 ArrayBuffer 数据
         * @param {number} [scale=2] - 渲染缩放比例（越大越清晰，默认 2）
         * @returns {Promise<string>} - 图片的 Base64 字符串
         */
        async pdfFirstPageToBase64(pdfSource, scale = 2) {
            console.log(pdfjs)
            try {
                // 加载 PDF 文档
                const pdfDoc = await pdfjs.getDocument(pdfSource).promise;
                
                // 检查是否有至少一页
                if (pdfDoc.numPages < 1) throw new Error('PDF 无有效页面');
                
                // 获取第一页（页码从 1 开始）
                const page = await pdfDoc.getPage(1);
                
                // 计算 Canvas 尺寸（基于页面视口和缩放比例）
                const viewport = page.getViewport({ scale });
                const canvas = document.createElement('canvas');
                const context = canvas.getContext('2d');
                canvas.width = viewport.width;
                canvas.height = viewport.height;
                
                // 渲染页面到 Canvas
                await page.render({
                    canvasContext: context,
                    viewport: viewport
                }).promise;
                
                // 转换为 PNG 格式的 Base64（可改为 'image/jpeg' 但可能丢失透明）
                return canvas.toDataURL('image/png');
            
            } catch (error) {
                console.error('转换失败:', error);
                throw error; // 抛出错误以便上层处理
            }
        },
        async convertPdf() {
            try {
              // 替换为你的 PDF 文件 URL（需支持 CORS）
              const pdfUrl = 'http://ea8.com/storage/20250809/mJI1754744266bqnOcf1.pdf';
              
              // 调用转换函数（等待完成）
              const base64 = await pdfFirstPageToBase64(pdfUrl, 2);
              
              // 显示结果（可选）
              $('body').append('<img id="resultImg" src="'+base64+'" alt="PDF 第一页"/>')
              console.log('Base64 结果:', base64);
              
            } catch (error) {
              alert('转换失败，请检查 PDF 地址或网络连接');
            }
        }
    }

    var bind = {
        /**
         * 双向绑定工具函数（Layui 表单）
         * @param {Object} model 数据模型（键为表单元素 name，值为初始值）
         * @param {String} formSelector 表单选择器（如 '#myForm'）
         */
        init(model, formSelector) {
            var $form = $(formSelector);
            var form = layui.form;
            Object.keys(model).forEach(function(key) {
                var $elem = $form.find('[name="' + key + '"]');
                if ($elem.length === 0) return; // 跳过不存在的元素
        
                var value = model[key];
                var tag = $elem[0].tagName.toLowerCase(); // 元素标签名
        
                // 根据元素类型设置值
                if (tag === 'input') {
                    elem.val(value);
                } else if (tag === 'select') {
                    $elem.val(value);
                    form.render('select'); // 下拉框需重新渲染
                } else if (tag === 'textarea') {
                    $elem.val(value);
                }
            });

            watch();
        
            // 返回更新视图的接口
            return {
                updateView: updateView
            };
        },
        
            // 监听表单变化 → 更新模型
        watch() {
            $form.on('input', 'input, textarea', function() {
                var key = $(this).attr('name');
                if (key && model.hasOwnProperty(key)) {
                model[key] = $(this).val();
                }
            });
        
            $form.on('select', 'select', function(data) {
                var key = $(this).attr('name');
                if (key && model.hasOwnProperty(key)) {
                model[key] = data.value;
                }
            });
        },
        
            // 模型变化 → 更新视图（外部调用）
        updateView() {
            Object.keys(model).forEach(function(key) {
                var $elem = $form.find('[name="' + key + '"]');
                if ($elem.length === 0) return;
        
                var value = model[key];
                var tag = $elem[0].tagName.toLowerCase();
        
                if (tag === 'input') {
                    $elem.val(value);
                } else if (tag === 'select') {
                    $elem.val(value);
                    form.render('select');
                } else if (tag === 'textarea') {
                    $elem.val(value);
                }
            });
        }
    }
    var obj = {

        index: function () {
            active.methods.table_init();
            active.methods.table_toolbar_active();
            ea.listen();

            // setTimeout(()=>{
            //     pdf.convertPdf();
            // }, 1000)
        },
        add1: function () {
            layui.util.on({
                AiOptimization: function (data) {
                    let layOn = $(data).attr('lay-on')
                    $(data).attr('lay-on', layOn + 'Loading')
                    aiOptimization(data)
                },
            });

            active.listen();
            $('input[name="p_type_sy"]').on('change', function () {
                checkTypeCreateHistoryHtml();
            })
            $('input[name="p_type_jq"]').on('change', function () {
                checkTypeCreateHistoryHtml();
            });

            layui.form.on('select(history_single)', function(data){
                console.log(data)
                $('#cost_sy').attr('lay-verify', '')
                $('#cost_jq').attr('lay-verify', '')
                if (data.value == 1) {
                    $('#cost_jq').attr('lay-verify', 'required')
                } else if (data.value == 2) {
                    $('#cost_sy').attr('lay-verify', 'required')
                }
            })

            function checkTypeCreateHistoryHtml() {
                var p_type_sy = $('input[name="p_type_sy"]').val();
                var p_type_jq = $('input[name="p_type_jq"]').val();
                var history_single = $('#history_single').val();
                var container = $('#history_single_div');

                console.log(container)
                container.empty();
                var label = '';
                var reqtxt = '';
                if (p_type_sy == 1 && p_type_jq != 2) {
                    label = '在我司有投保交强险';
                    reqtxt = '请选择在我司有投保交强险';
                } else if (p_type_sy != 1 && p_type_jq == 2) {
                    label = '在我司有投保商业险';
                    reqtxt = '请选择在我司有投保商业险';
                }
                html = `
                        <label class="layui-form-label">${label}</label>
                        <div class="layui-input-block">
                            <select id="history_single" name="history_single" lay-verify="required" lay-filter="history_single" lay-reqtext="${reqtxt}">
                                <option value=""></option>
                                <option value="2">否</option>
                                <option value="1">是</option>
                            </select>
                        </div>
                    `;
                container.html(html);
                layui.form.render('select');
            }
            ea.listen('', '', '', '', 
                function(init, callback){
                    var p_type_sy = $('input[name="p_type_sy"]').val();
                    var p_type_jq = $('input[name="p_type_jq"]').val();
                    var p_type_jc = $('input[name="p_type_jc"]').val();
                    init.wait_submit = false;
                    if (!p_type_sy && !p_type_jq && !p_type_jc) {
                        ea.msg.error('请选择文件识别后提交');
                        return false;
                    }
                    var history_single = $('#history_single').val();
                    if (history_single == 1) {
                        var cost_jq = $('#cost_jq').val();
                        if (cost_jq == '' || cost_jq <= 0) {
                            ea.msg.error('请输入交强险金额');
                            return false;
                        }
                    }
                    callback();
                    return true;
                });
        },

        addOrSupplement: function(option){
            option = option || {};
            

            var o = {
                ocr_after_render(data){
                    // 如果是单商就查询历史单交记录
                    var insurer = data[0].insurer;
                    var carno = data[0].carno;
                    var start_at = data[0].start_at;
                    var car_type = 0;
                    var agent = '';
                    var d = data.findIndex(item => item.type == 1);
                    if (d == -1) {
                        var d = data.findIndex(item => item.type == 0);
                    }
                    console.log(d)
                    if (d != -1) {
                        car_type = data[d].car_type;
                        agent = data[d].agent;
                    }
                    // var is_same = false;
                    var is_type = false;
                    for (var i = 0; i < data.length; i++){
                        if (data[i].type == 0) {
                            is_type = true;
                        }
                        if (data[i].insurer != insurer || data[i].carno != carno) {
                            is_same = true;
                            break;
                        }
                    }
                    // if (is_same) {
                    //     ea.msg.error('请确保文件中所有保单都是同一个投保人同一个车牌');
                    //     return false;
                    // }
                    for (var i = 0; i < data.length; i++) {
                        data[i]['chd_rating'] = 16;
                        data[i]['auto_coefficient'] = 0.8;
                        if (data[i].type == 2) {
                            data[i]['car_type'] = car_type;
                            data[i]['agent'] = agent;
                        }
                    }
                    currentData.data = data;
                    // layui.table.reload(table_render_id, {
                    //     data: data,
                    // });

                    // 单商查询历史单交记录
                    if (!is_type) {
                        ea.request.fetch(ea.url(init.get_history_List_url), {
                            insurer: insurer,
                            carno: carno,
                            start_at: start_at,
                        })
                        .then(res => {
                            if (res.code == 1 && !res.data) {
                                var item = res.data;
                                $('#bind_history_policy_id').html('<option value="'+item.id+'" selected>'+item.create_at+'</option>');
                                layui.form.render('select');
                            }
                        })
                    }
                }
            }
            var flag = true; // 防止重复提交
            layui.util.event('lay-active', {
                ocr_pdf: function(){
                    var uploadName = $(this).attr('data-analysispdf'),
                    elem = "input[name='" + uploadName + "']";
                    if (!flag) {
                        return false;
                    }
                    flag = false;
                    var pdf = $(elem).val();
                    var pdf_arr = pdf.split('|');
                    if (pdf_arr.length == 0 || pdf_arr[0] == '') {
                        ea.msg.error('请上传文件');
                        flag = true;
                        return false;
                    }
                    var requsetQueue = [];
                    var lay_index = ea.msg.loading('正在处理中，请稍后...');
                    if (ocr_type == 0) {
                        for (var i = 0; i < pdf_arr.length; i++) {
                            requsetQueue.push({url: "pdf2ImgOne", data: {pdf: pdf_arr[i]}});
                        }
                        // 逐个PDF文件转换为图片
                        requsetQueue.reduce((prevPromise, currentReq)=>{
                            return prevPromise.then((prevRes)=>{
                                return ea.request.fetch(currentReq.url, currentReq.data).then(res => {
                                    prevRes.push({url: "ocrImg", data: res.data});
                                    return prevRes;
                                })
                            })
                        }, Promise.resolve([]))
                        .then(finalRes => {
                            // 逐个图片识别
                            finalRes.reduce((prevPromise, currentReq)=>{
                                return prevPromise.then((prevRes)=>{
                                    return ea.request.fetch(currentReq.url, currentReq.data).then(res => {
                                        if (res.code == 0) {
                                            ea.msg.error(res.message)
                                        }
                                        prevRes.push(res.data);
                                        return prevRes;
                                    })
                                })
                            }, Promise.resolve([]))
                            .then(finalRes1 => {
                                console.log("finalRes1", finalRes1);
    
                                o.ocr_after_render(finalRes1);
    
                                ea.msg.close(lay_index);
                                flag = true;
                            })
                            .catch(err => {
                                ea.msg.error("转换失败,请重试", function(){
                                    ea.msg.close(lay_index);
                                });
                                flag = true;
                            })
                        })
                        .catch(err => {
                            ea.msg.error("转换失败,请重试", function(){
                                ea.msg.close(lay_index);
                            });
                            flag = true;
                        });

                    } else {
                        for (var i = 0; i < pdf_arr.length; i++) {
                            requsetQueue.push({url: "ocrImg", data: {file: pdf_arr[i]}});
                        }
                        requsetQueue.reduce((prevPromise, currentReq)=>{
                            return prevPromise.then((prevRes)=>{
                                return ea.request.fetch(currentReq.url, currentReq.data).then(res => {
                                    if (res.code == 0) {
                                        ea.msg.error(res.message)
                                    }
                                    prevRes.push(res.data);
                                    return prevRes;
                                })
                            })
                        }, Promise.resolve([]))
                        .then(finalRes1 => {
                            console.log("finalRes1", finalRes1);

                            o.ocr_after_render(finalRes1);

                            ea.msg.close(lay_index);
                            flag = true;
                        })
                        .catch(err => {
                            ea.msg.error("转换失败,请重试", function(){
                                ea.msg.close(lay_index);
                            });
                            flag = true;
                        })
                    }
                },
                save: function(){
                    var tableCache = layui.table.cache[table_render_id]; // 获取表格缓存
                    if (tableCache.length == 0) {
                        ea.msg.error('请先识别文件');
                        return false;
                    }
                    var item0 = tableCache[0];
                    var is_same = false;
                    var msg = '';
                    var is_type = false;
                    for (var i = 1; i < tableCache.length; i++) {
                        var item = tableCache[i];
                        if (item.insurer != item0.insurer) {
                            is_same = true;
                            msg = '投保人不一致';
                            break;
                        }
                        if (item.carno != item0.carno) {
                            is_same = true;
                            msg = '车牌号不一致';
                            break;
                        }
                        if (item.create_at != item0.create_at) {
                            is_same = true;
                            msg = '出单日期不一致';
                            break;
                        }
                        if (!/^\d{4}-\d{2}-\d{2}$/.test(item.create_at)) {
                            is_same = true;
                            msg = '出单日期格式不正确,如：2022-01-01';
                            break;
                        }
                    }
                    if (is_same) {
                        ea.msg.error(msg);
                        return false;
                    }
                    for (var i = 1; i < tableCache.length; i++) {
                        var item = tableCache[i];
                        if (item.type == 0) {
                            is_type = true;
                            break;
                        }
                    }
                    var is_history_single = $('#is_history_single').val();
                    var bind_history_policy_id = $('#bind_history_policy_id').val();
                    var cost_jq = $('#cost_jq').val();
                    // 提交单商 -> 在我司有投保交强险 -> 未绑定历史保单 | 未填写交强险保额
                    if (is_type && is_history_single == 1 && (bind_history_policy_id == '' || cost_jq == '')) {
                        ea.msg.error('请先选择在我司购买的交强险或填写交强险保额');
                        return false;
                    }
                    if (cost_jq > 0 && cost_jq < 665) {
                        ea.msg.error('交强险保额不能低于665');
                        return false;
                    }
                    var formdata = {
                        data: tableCache, 
                        is_history_single: is_history_single,
                        bind_history_policy_id: bind_history_policy_id,
                        cost_jq: cost_jq,
                    }
                    if (option.url == init.supplement_url) {
                        formdata.id = $('#id').val();
                    }
                    ea.request.fetch(ea.url(option.url), {
                        data: formdata,
                        type: 'post'
                    }).then(res => {
                        if (res.code == 1) {
                            ea.msg.success(res.msg);
                            // ea.msg.closeAll();
                            ea.api.closeCurrentOpen({
                                refreshTable: true
                            });
                        } else {
                            ea.msg.error(res.msg);
                        }
                    })
                }
            })
            var table_render_id = 'currentTableRenderId';
            var data = {data: []};
            
            var currentData = {data: []};
            var tb = layui.table.render({
                elem: '#currentTable',
                id: table_render_id,
                data: currentData.data,
                cols: [[
                    // {type: "checkbox", search: false},
                    {field: 'company', minWidth: 80, title: '保险公司', search: false, edit: 'text'},
                    {field: 'type', minWidth: 80, title: '保险类型', search: false, templet: function(d){
                        return d.type == 0 ? '交强' : d.type == 1 ? '商业' : '驾乘';
                    }},
                    {field: 'agent', minWidth: 80, title: '代理人', search: false, edit: 'text'},
                    {field: 'insurer', minWidth: 80, title: '投保人', search: false, edit: 'text'},
                    {field: 'carno', minWidth: 80, title: '车牌号', search: false, edit: 'text'},
                    {field: 'car_type', minWidth: 100, title: '车辆类型', search: false, templet: function(d){
                        var html = `<select class="lay-select" data-id="${d.type + '-' + d.num}" name="car_type${d.type + d.num}" data-field="car_type" lay-filter="car_type" lay-append-to="body">`;
                        html += `<option value="">请选择车辆类型</option>`;
                        for (var i = 0; i < carTypeSelects.length; i++) {
                            html += `<option value="${carTypeSelects[i].id}" ${d.car_type == carTypeSelects[i].id ? 'selected' : ''}>${carTypeSelects[i].title}</option>`;
                        }
                        html += '</select>';
                        return html;
                    }},
                    {field: 'chd_rating', minWidth: 80, title: '车慧达评分', search: false, edit: 'text'},
                    {field: 'auto_coefficient', minWidth: 80, title: '自主系数', search: false, edit: 'text'},
                    {field: 'num', minWidth: 80, title: '保单号', search: false, edit: 'text'},
                    {field: 'cost', minWidth: 80, title: '保费', search: false, edit: 'text'},
                    {field: 'vv_tax', minWidth: 80, title: '车船税', search: false, edit: 'text'},
                    {field: 'is_car_damage', minWidth: 100, title: '车损', lineStyle: 'text-align: center', search: false, templet: function(d){
                        return `
                        <select class="lay-select" data-id="${d.type + '-' + d.num}" name="is_car_damage_${d.type + d.num}" data-field="is_car_damage" lay-filter="is_car_damage" lay-append-to="body">
                        <option value="0" ${d.is_car_damage == 0 ? 'selected' : ''}>否</option>
                        <option value="1" ${d.is_car_damage == 1 ? 'selected' : ''}>是</option>
                        </select>
                        `;
                    }},
                    {field: 'start_at', minWidth: 170, title: '起保日期', search: false, templet: function(d){
                        return `<input class="layui-input laydatetime" placeholder="选择日期" value="${d.start_at}" data-id="${d.type + '-' + d.num}" data-field="start_at">`;
                    }},
                    {field: 'end_at', minWidth: 170, title: '止保日期', search: false, templet: function(d){
                        return `<input class="layui-input laydatetime" placeholder="选择日期" value="${d.end_at}" data-id="${d.type + '-' + d.num}" data-field="end_at">`;
                    }},
                    {field: 'third_party_cost', minWidth: 80, title: '第三者保额', search: false, edit: 'text'},
                    {field: 'create_at', minWidth: 110, title: '出单时间', search: false, edit: 'text'},
                    {field: 'remark', minWidth: 110, title: '备注', edit: 'text', },
                    // {field: 'create_at', minWidth: 160, title: '出单时间', search: false, templet: function(d){
                    //     return `<input class="layui-input laydate" placeholder="选择日期" value="${d.create_at}" data-id="${d.type + '-' + d.num}" data-field="create_at">`;
                    // }},
                ]],
                done: function () {
                    layui.laydate.render({
                        elem: '.laydate',
                        type: 'date',
                        format: 'yyyy-MM-dd',
                        trigger: 'click',
                        change: function(value, date, endDate){
                        }
                    });
                    layui.laydate.render({
                        elem: '.laydatetime',
                        type: 'datetime',
                        format: 'yyyy-MM-dd HH:mm:ss',
                        trigger: 'click',
                        change: function(value, date, endDate){
                            var $input = $(this.elem);
                            var rowId = $input.attr('data-id'); // 获取行唯一标识（id）
                            var field = $input.attr('data-field'); // 获取行唯一标识（id）
                            console.log('change',rowId, value, field)
                            updateTableModel(rowId, value, field);
                        }
                    });
                    layui.form.render('select');
                }
            });
            Object.defineProperty(currentData, 'data', {
                set: function (val) {
                    tb.reload({
                        data: val
                    });
                    data = val;
                    showForm();
                },
                get: function () {
                    return data;
                }
            });

            function showForm(){
                if (data.length > 0) {
                    $('#pdf_info').removeClass('layui-hide');
                } else {
                    $('#pdf_info').addClass('layui-hide');
                }
            }
            showForm();
            
            layui.form.on('select(is_car_damage)', function(data) {
                var rowId = data.elem.getAttribute('data-id'); // 获取行唯一标识（id）
                var field = data.elem.getAttribute('data-field'); // 获取行唯一标识（id）
                console.log(field, rowId)
                updateTableModel(rowId, data.value, field);
            });
            layui.form.on('select(car_type)', function(data) {
                var rowId = data.elem.getAttribute('data-id'); // 获取行唯一标识（id）
                var field = data.elem.getAttribute('data-field'); // 获取行唯一标识（id）
                console.log(field, rowId)
                updateTableModel(rowId, data.value, field);

            });
            function updateTableModel(rowId, newValue, field) {
                // 查找当前行在数据模型中的索引
                var tableCache = layui.table.cache[table_render_id]; // 获取表格缓存
                var rowIndex = tableCache.findIndex(item => (item.type + '-' + item.num) == rowId);
                // console.log(rowIndex)
                if (rowIndex !== -1 && tableCache) {
                    tableCache[rowIndex][field] = newValue;
                }
                // console.log(tableCache)
            }
        },
        add: function () {
            layui.util.on({
                AiOptimization: function (data) {
                    let layOn = $(data).attr('lay-on')
                    $(data).attr('lay-on', layOn + 'Loading')
                    aiOptimization(data)
                },
            });
            obj.addOrSupplement({url: init.add_url})
            // active.listen();
            ea.listen();
        },
        edit: function () {
            layui.util.on({
                AiOptimization: function (data) {
                    let layOn = $(data).attr('lay-on')
                    $(data).attr('lay-on', layOn + 'Loading')
                    aiOptimization(data)
                },
            });
            ea.listen();
        },
        edit1: function () {
            layui.util.on({
                AiOptimization: function (data) {
                    let layOn = $(data).attr('lay-on')
                    $(data).attr('lay-on', layOn + 'Loading')
                    aiOptimization(data)
                },
            })

            active.listen();
            
            ea.listen('', '', '', '', 
                function(init, callback){
                    return false;
                    callback();
                });
        },
        supplement: function () {
            layui.util.on({
                AiOptimization: function (data) {
                    let layOn = $(data).attr('lay-on')
                    $(data).attr('lay-on', layOn + 'Loading')
                    aiOptimization(data)
                },
            });
            console.log(this)

            obj.addOrSupplement({url: init.supplement_url})
            ea.listen();
        },
        stock: function () {
            ea.listen();
        },
        recycle: function () {
            init.index_url = init.recycle_url;
            ea.table.render({
                init: init,
                toolbar: ['refresh',
                    [{
                        class: 'layui-btn layui-btn-sm',
                        method: 'get',
                        field: 'id',
                        icon: 'fa fa-refresh',
                        text: '全部恢复',
                        title: '确定恢复？',
                        auth: 'recycle',
                        url: init.recycle_url + '?type=restore',
                        checkbox: true
                    }, {
                        class: 'layui-btn layui-btn-danger layui-btn-sm',
                        method: 'get',
                        field: 'id',
                        icon: 'fa fa-delete',
                        text: '彻底删除',
                        title: '确定彻底删除？',
                        auth: 'recycle',
                        url: init.recycle_url + '?type=delete',
                        checkbox: true
                    }], 'export',
                ],
                cols: [[
                    {type: "checkbox"},
                    {field: 'id', width: 80, title: 'ID', searchOp: '='},
                    {field: 'sort', width: 80, title: '排序', edit: 'text'},
                    {field: 'cate_id', minWidth: 80, title: '商品分类', search: 'select', selectList: cateSelects, laySearch: true},
                    {field: 'title', minWidth: 80, title: '商品名称'},
                    {field: 'logo', minWidth: 80, title: '分类图片', search: false, templet: ea.table.image},
                    {field: 'status', title: '状态', width: 85, selectList: {0: '禁用', 1: '启用'}},
                    // 演示多选，实际数据库并无 status2 字段，搜索后会报错
                    {
                        field: 'status2', title: '演示多选', width: 105, search: 'xmSelect', selectList: {1: '模拟选项1', 2: '模拟选项2', 3: '模拟选项3', 4: '模拟选项4', 5: '模拟选项5'},
                        searchOp: 'in', templet: function (res) {
                            // 根据自己实际项目进行输出
                            return res?.status2 || '模拟数据'
                        }
                    },
                    {field: 'create_time', minWidth: 80, title: '创建时间', search: 'range'},
                    {field: 'delete_time', minWidth: 80, title: '删除时间', search: 'range'},
                    {
                        width: 250,
                        title: '操作',
                        templet: ea.table.tool,
                        operat: [
                            [{
                                title: '确认恢复？',
                                text: '恢复数据',
                                filed: 'id',
                                url: init.recycle_url + '?type=restore',
                                method: 'get',
                                auth: 'recycle',
                                class: 'layui-btn layui-btn-xs layui-btn-success',
                            }, {
                                title: '想好了吗？',
                                text: '彻底删除',
                                filed: 'id',
                                method: 'get',
                                url: init.recycle_url + '?type=delete',
                                auth: 'recycle',
                                class: 'layui-btn layui-btn-xs layui-btn-normal layui-bg-red',
                            }]]
                    }
                ]],
            });
            ea.listen();
        },

        upload: function () {
            ea.listen();
        },

        renewals: function () {
            active.methods.table_init({
                toolbar_custcom: [
                    {
                        text: '关闭通知',
                        url: init.set_policy_notice_url,
                        method: 'none',
                        auth: 'setNotice',
                        class: 'layui-btn layui-btn-normal layui-btn-sm',
                        icon: '',
                        extend: 'lay-active="setNotice" data-url="'+ init.set_policy_notice_url +'" data-width="90%" data-height="95%"',
                    },
                ],
                where: {
                    is_renewal: 1,
                },
                searchValue: {
                    renewal: 2
                } 
            })
            active.methods.table_toolbar_active();
            ea.listen();
        }
    };

    function aiOptimization(data) {
        let layOn = $(data).attr('lay-on')
        let title = $('input[name="title"]').val()

        // 告诉AI 你需要做什么
        let message = `优化这个标题 ${title}`

        if ($.trim(title) === '') {
            ea.msg.error('标题不能为空', function () {
                $(data).attr('lay-on', layOn.split('Loading')[0])
            })
            return false
        }
        let url = ea.url('insurance.pollicy/aiOptimization')
        ea.request.post({url: url, data: {message: message}}, function (res) {
            let content = res.data?.choices[0]?.message?.content
            // stream 为true 时，AI 内容会逐字输出
            let stream = true
            ea.ai.chat(content, {stream: stream}, function () {
                $(data).attr('lay-on', layOn.split('Loading')[0])
            })
        }, function (error) {
            ea.msg.error(error.msg, function () {
                $(data).attr('lay-on', layOn.split('Loading')[0])
            })
        })
    }

    return obj;
});